import { Injectable } from '@nestjs/common';
import { CreatePlanDto } from './dto/create-plan.dto';
import { UpdatePlanDto } from './dto/update-plan.dto';
import { PrismaService } from '../prisma/prisma.service';
import { Plan } from '@prisma/client';
import { Prisma } from '@prisma/client';
import { log } from 'console';

@Injectable()
export class PlanService {
  constructor(private prisma: PrismaService) {}
  async create(createPlanDto: CreatePlanDto,userid:number) {
    const planData:any = {
      createdAt: new Date(createPlanDto.planDate),
      type: createPlanDto.type,
      is_remind: createPlanDto.isRemind?1:0,
      is_done: createPlanDto.isDone?1:0,
      plan_name: createPlanDto.planName,
    };
   
    const familys = createPlanDto.selectedContacts?.map((contact) => ({ id: contact })) || [];
   
    if (createPlanDto.planId !== undefined) {
      planData.plan_id = createPlanDto.planId;
    }
    return await this.prisma.plan.upsert({
      where: createPlanDto.id != undefined ? { id: createPlanDto.id } : {
        plan_id: planData.plan_id,
      },
      update: {
        ...planData,
        familys: {
          set: familys as unknown as Prisma.FamilyWhereUniqueInput[],
        },
      },
      create: {
        ...planData,
        user_id: userid,
        familys: {
          connect: familys as unknown as Prisma.FamilyWhereUniqueInput[],
        },
      },
    });
  }
  

  async findAll(data: {type: number },id:number) {
    return await this.prisma.plan.findMany({
      where: {
        user_id: id,
        type: data.type,
      },
      include: {
        familys: true,
      },
    });
  }

  findOne(id: number) {
    return `This action returns a #${id} plan`;
  }

  update(id: number, updatePlanDto: UpdatePlanDto) {
    return `This action updates a #${id} plan`;
  }

  async remove(id: number) {
    // 先断开所有关联关系
    await this.prisma.plan.update({
      where: { id },
      data: {
        familys: {
          set: [], 
        },
      },
    });
    return await this.prisma.plan.delete({
      where: { id },
    });
  }
}
